<template>
    <page-header-wrapper>
      <div class="card">
        <!-- 添加标题和描述 -->
        <div class="header">
          <h1 class="title">AI 对话助手</h1>
          <p class="description">与智能 AI 进行实时对话，获取学习建议、解答问题和更多。</p>
        </div>
  
        <div class="chat-body-info">
          <div v-for="(msg, index) in msgList" :key="index">
            <div
              class="chat-info"
              style="justify-content: flex-end"
              v-if="msg.role == 'user'"
            >
              <div class="ai-con user-msg">
                {{ msg.content }}
              </div>
              <div class="avatar">
                <img
                  src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                  class="avatar"
                />
              </div>
            </div>
            <div class="chat-info" v-else>
              <div class="avatar">
                <img src="@/assets/images/ai.jpeg" class="avatar" />
              </div>
              <div class="ai-con" v-html="parsMarked(msg.content)"></div>
            </div>
          </div>
          <div class="chat-info" v-if="streamingText">
            <div class="avatar">
              <img src="@/assets/images/ai.jpeg" class="avatar" />
            </div>
            <div class="ai-con">
              <Typed :typedList="streamingText" :streaming="streaming" />
            </div>
          </div>
          <div class="chat-info" v-if="streaming">
            <div class="avatar">
              <img src="@/assets/images/ai.jpeg" class="avatar" />
            </div>
            <div class="ai-con">
              <div class="loading">
                <div></div>
                <div></div>
                <div></div>
                <div></div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <div class="chat-input">
            <input
              type="text"
              class="m-input"
              placeholder="请输入消息..."
              v-model="sendMsg"
              @keyup.enter="handleSubmit"
            />
            <a-button class="send-btn" @click="handleSubmit">发送</a-button>
          </div>
        </div>
      </div>
    </page-header-wrapper>
  </template>
  
  <script>
  import Typed from "@/components/Typed.vue";
  import { marked } from "marked";
  import axios from "axios";
  export default {
    components: {
      Typed,
    },
  
    data() {
      return {
        userInfo: undefined,
        userType: undefined,
        streamingText: "",
        text: "",
        streaming: false,
        recommend: false,
        msgList: [],
        msgJsonList: [],
        typewriterQueue: [],
        typewriterInterval: null,
        sendMsg: "",
        jsonAnswer: {
          location: "",
          jobName: "",
          content: "",
          isNeedJob: false,
        },
        jobList: [],
        showJobDetail: false, //展示岗位详情
        jobDetail: undefined, //岗位详情信息
        presetPrompts: [],
        //系统数据库信息
        sysInfo: {},
        sysLoading: false,
      };
    },
    mounted() {
      const prompt = {
        content: `你是学习管理系统的AI聊天助手，请督促我学习。`,
        role: "system",
      };
      this.msgJsonList.push(prompt);
    },
    methods: {
      parsMarked(msg) {
        return marked(msg);
      },
      async stream(prompt, history = [], stream) {
        this.streaming = true;
        const res = await axios.post(
          "/keya",
          {
            messages: [
              ...history,
              {
                role: "user",
                content: prompt,
              },
            ],
            model: "4.0Ultra",
            stream: true,
            top_p: 0.2,
          },
          {
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer EuNgmRXDJChPWqDjYifD:ZMlPIGXJgbgsrdbQJblI`,
            },
            onDownloadProgress: (progressEvent) => {
              const textChunk = progressEvent.event.currentTarget.response;
              const textArray = textChunk.split("\n").filter((s) => s && s.trim());
              this.typewriterQueue = [];
              textArray.forEach((element) => {
                if (element.includes("[DONE]")) return;
                const result = this.getContentFromStr(element);
                if (result && result.choices && result.choices.length > 0) {
                  if (result.choices[0].finish_reason == "stop") return;
                  else {
                    this.typewriterQueue.push(
                      ...result.choices[0].delta.content.split("")
                    );
                  }
                  this.streaming = false;
                } else {
                  if (result.error) {
                    this.streaming = false;
                    this.msgJsonList.splice(this.msgJsonList.length - 1, 1);
                    this.msgList.splice(this.msgList.length - 1, 1);
                    this.$modal.msgError(result.error);
                  }
                }
              });
              this.streamingText = this.typewriterQueue.join("");
            },
          }
        );
      },
      getContentFromStr(str) {
        const jsonStr = str.trim().replace("data:", "");
        try {
          return JSON.parse(jsonStr);
        } catch {
          return null;
        }
      },
      handleSubmit() {
        if (this.streaming) {
          this.$modal.msgError("AI 正在处理中，请稍后再试~");
          return;
        }
        if (this.streamingText) {
          this.msgList.push({ role: "assistant", content: this.streamingText });
          this.msgJsonList.push({
            role: "assistant",
            content: JSON.stringify(this.jsonAnswer),
          });
          this.streamingText = "";
        }
        this.msgList.push({ role: "user", content: this.sendMsg });
        this.stream(this.sendMsg, this.msgJsonList, true);
        this.sendMsg = "";
      },
    },
  };
  </script>
  
  <style scoped>
  /* 标题与描述样式 */
  .header {
    text-align: center;
    margin-bottom: 20px;
  }
  .title {
    font-size: 24px;
    font-weight: bold;
    color: #2c3e50;
  }
  .description {
    font-size: 14px;
    color: #606266;
    margin-top: 5px;
  }
  
  /* 其他样式保持不变 */
  .card {
    padding: 24px;
    background-color: white;
    border: 1px solid #ebeef5;
    border-radius: 12px;
    height: 600px;
    margin: 20px 0px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  .chat-body-info {
    padding: 20px 30px;
    overflow-y: auto;
    flex-grow: 1;
    scroll-behavior: smooth;
  }
  .chat-info {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
  }
  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
  }
  .ai-con {
    max-width: 70%;
    margin: 0 15px;
    padding: 12px 18px;
    border-radius: 15px;
    background-color: #f5f7fa;
    color: #2c3e50;
    font-size: 14px;
  }
  .user-msg {
    background-color: #409eff;
    color: white;
  }
  .chat-input {
    display: flex;
    align-items: center;
    background: white;
    border-radius: 12px;
    padding: 8px;
    border: 1px solid #ebeef5;
  }
  .m-input {
    flex: 1;
    border: none;
    padding: 10px 15px;
    font-size: 14px;
  }
  .send-btn {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    color: white;
    border-radius: 8px;
    padding: 10px 20px;
    cursor: pointer;
  }
  </style>